//
//  LoginViewController.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/11/27.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit
enum FunctionButtonForLoginPage: Int {
    case back = 1000
    case loginHeaderByAccount
    case LoginHeaderByPhone
    case Login
    case gainCode
    case register
    case forgetPassword
}
class LoginViewController: UIViewController {
    @IBOutlet var functionButtons: [UIButton]!
    @IBOutlet weak var lineView: UIView!
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var gainCodeButton: UIButton!
    static let sharedLoginScene: LoginViewController = {
        let instance = (UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginScene") as! LoginViewController)
        return instance
    }()
    let lineLayer = CALayer.init()
    var loginWay: FunctionButtonForLoginPage? {
        didSet {
            for itemButton in functionButtons {
                let tagValue: FunctionButtonForLoginPage = FunctionButtonForLoginPage(rawValue: itemButton.tag)!
                if loginWay == tagValue {
                    itemButton.setTitleColor(.red, for: .normal)
                }else {
                    itemButton.setTitleColor(.darkGray, for: .normal)
                }
            }
            switch loginWay {
            case .loginHeaderByAccount:
                self.accountTextField.placeholder = "手机号码/邮箱"
                self.passwordTextField.placeholder = "请输入密码"
                UIView.animate(withDuration: 1, animations: {
                    self.lineLayer.frame = CGRect(x: self.lineView.bounds.size.width/2, y: 0, width: self.lineView.bounds.size.width/2, height: self.lineView.bounds.size.height)
                }) { (true) in
                    self.lineLayer.frame = CGRect(x: 0, y: 0, width: self.lineView.bounds.size.width/2, height: self.lineView.bounds.size.height)
                }
                self.gainCodeButton.isHidden = true
                break
            case .LoginHeaderByPhone:
                self.accountTextField.placeholder = "手机号码"
                self.passwordTextField.placeholder = "请输入验证码"
                UIView.animate(withDuration: 1, animations: {
                    self.lineLayer.frame = CGRect(x: 0, y: 0, width: self.lineView.bounds.size.width/2, height: self.lineView.bounds.size.height)
                }) { (true) in
                    self.lineLayer.frame = CGRect(x: self.lineView.bounds.size.width/2, y: 0, width: self.lineView.bounds.size.width/2, height: self.lineView.bounds.size.height)
                }
                self.gainCodeButton.isHidden = false
                break
            default:
                break
            }
        }
    }
    var tempCode: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.loginWay = .loginHeaderByAccount
        self.lineLayer.frame = CGRect(x: 0, y: 0, width: self.lineView.bounds.size.width/2, height: self.lineView.bounds.size.height)
        self.lineView.layer.insertSublayer(self.lineLayer, at: 0)
        self.lineLayer.backgroundColor = UIColor.red.cgColor
    }
    @IBAction func touchButtonAction(_ sender: UIButton) {
        let tagValue: FunctionButtonForLoginPage = FunctionButtonForLoginPage(rawValue: sender.tag)!
        switch tagValue {
        case .back:
            print("返回")
            self.hide()
            break
        case .loginHeaderByAccount:
            print("账户登录")
            self.loginWay = .loginHeaderByAccount
            break
        case .LoginHeaderByPhone:
            self.loginWay = .LoginHeaderByPhone
            print("手机登录")
            break
        case .Login:
            print("登录")
            switch loginWay {
            case .loginHeaderByAccount:
                break
            case .LoginHeaderByPhone:
                if tempCode.count != 0 && tempCode == self.passwordTextField.text! {
                    UploadingData.sharedUploadingData.uploadData("http://api.cqvip.com/qikanapp/QucikLogin.ashx", "userName=\(self.accountTextField.text!)", .post)
                    UploadingData.sharedUploadingData.success = { (data, urlStr) in
                        let result = try! JSONDecoder().decode(AccountDictModel.self, from: data!)
                        print("登录成功!!!!\(result)")
                        NotificationCenter.default.post(name: Notification.Name(rawValue: "updateAccountInfo"), object: nil, userInfo: ["account":result])
                    }
                }else {
                    AlertView.showStatus("验证码不正确!")
                }
               break
            default:
                break
            }
            break
        case .gainCode:
            print("获取验证码")
            if self.accountTextField.text?.count == 0 || self.accountTextField.text?.count != 11 {
                AlertView.showStatus("请输入正确的手机号码!")
            }else { UploadingData.sharedUploadingData.uploadData("http://api.cqvip.com/qikanapp/SendMessage.ashx", "phone=\(self.accountTextField.text!)", .post)
                           UploadingData.sharedUploadingData.success = { (data, urlStr) in
                               let result = try! JSONDecoder().decode(CodeModel.self, from: data!)
                            print("收到的验证码:\(result)")
                               self.tempCode = result.result
                           }
            }
            break
        case .register:
            print("账号注册")
            break
        case .forgetPassword:
            print("忘记密码")
            break
        }
    }
}
extension LoginViewController {
    func show(from scene: UIViewController) {
        scene.present(self, animated: true, completion: nil)
    }
    func hide() {
        self.dismiss(animated: true, completion: nil)
    }
}
extension LoginViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return textField.resignFirstResponder()
    }
}
struct CodeModel: Codable {
    var result: String
}
struct Account: Codable {
    var userName: String
    var userid: Int
    var AccountTypeID: Int
    var organUserid: Int
    var groupId: Int
    var userUnit: String
    var userType: Int
    var userNature: Int
    var loginInfo: String
    var status: String
    var suid: String
    var userNick: String
    var qkdyFlag: Int
    var textTransferFlag: Int
    //var right: String
    var right_XML: String
}
struct AccountDictModel: Codable {
    var state: String
    var msg: String
    var datetime: String
    var Count: Int
    var message: String
    var tokens: String
    var result: AccountResultModel
}
struct AccountResultModel: Codable {
    var obj: Account
}
